<?php

namespace app\index\controller;

use app\admin\model\Admin;
use app\common\controller\Frontend;
use app\common\logic\OrderLogic;
use app\common\model\FreezeRecord;
use app\common\model\Member;
use app\common\model\Message;
use app\common\model\MoneyRecord;
use app\common\model\Order;
use app\common\model\OrderCommission;
use app\common\model\PayLog;
use app\job\Clue;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use think\Log;
use think\Queue;
use think\Request;

class Wechat extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $OrderLogic;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->OrderLogic = new OrderLogic();
    }


    public function wechat_notify()
    {
        $app = Factory::payment(config('wechat.payment'));
        $response = $app->handlePaidNotify(function($message, $fail) use ($app) {
            Log::info($message);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Order::get(['order_sn'=>$message['out_trade_no']]);
            if (empty($order) || $order['order_status'] !== Order::ORDER_STATUS_WAIT_PAY) { // 如果订单不存在 或者 订单已经支付过了
                return true;// 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    Db::startTrans();
                    try{
                        $order = $this->OrderLogic->updateOrder($order,$order->pay_type,$message['transaction_id']);// 更新订单
                        if ($order->pay_type == Order::PAY_TYPE_WECHAT_AND_BALANCE){ //如果是组合支付则需要扣除余额，并做充值折扣判断
                            $member = Member::get($order->member_id);
                            $balance = bcsub($member->balance, $order->balance_money, 2);
                            if ($balance <= 0){
                                $member->discount = 1;
                            }
                            $member->balance = $balance;
                            $member->save();
                            // 会员收支记录
                            MoneyRecord::create(['member_id'=> $order->member_id,'type'=> MoneyRecord::TYPE_SPEND, 'money'=> $order->pay_amount, 'balance'=> model('member')->where('id', $order['member_id'])->value('balance') ?? 0, 'order_id' => $order->id, 'detail_type' => MoneyRecord::DETAIL_TYPE_ORDER, 'remark'=> '订单组合支付']);
                        }else{
                            // 会员收支记录
                            MoneyRecord::create(['member_id'=> $order->member_id,'type'=> MoneyRecord::TYPE_SPEND, 'money'=> $order->pay_amount, 'balance'=> model('member')->where('id', $order['member_id'])->value('balance') ?? 0, 'order_id' => $order->id, 'detail_type' => MoneyRecord::DETAIL_TYPE_ORDER, 'remark'=> '订单组合支付']);
                        }

                        PayLog::payFinish($message);
                        OrderCommission::addRecord($order->id);

                        Db::commit();
                        $this->OrderLogic->send_message($order->id);
                        Queue::push(Clue::class,['member_id'=>$order->member_id,'event_type'=>2,'props'=>['pay_amount'=>intval($order->pay_amount * 100)]],'message');//付费
                        return true;// 返回处理完成
                    }catch (Exception $e){
                        Db::rollback();
                        Log::error('支付回调处理失败' . $e->getMessage());
                    }
                } elseif ($message['result_code'] === 'FAIL') {// 用户支付失败
                    return false;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });
        $response->send();
    }

    public function recharge_notify()
    {
        $app = Factory::payment(config('wechat.payment'));
        $response = $app->handlePaidNotify(function($message, $fail) use ($app) {
            Log::info($message);
            $payOrder = PayLog::where('order_sn', $message['out_trade_no'])->find();
            if (empty($payOrder) || $payOrder['status'] !== 1) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    bcscale(2);
                    Db::startTrans();
                    try{
                        $member = Member::get($payOrder['member_id']);
                        // 会员收支记录
                        MoneyRecord::create([ // 充值记录
                            'member_id'   => $payOrder['member_id'],
                            'type'        => MoneyRecord::TYPE_INCOME,
                            'detail_type' => MoneyRecord::DETAIL_TYPE_RECHARGE,
                            'money'       => $message['total_fee']/100,
                            'balance'     => bcadd($member->balance, $message['total_fee']/100),
                            'remark'      => '微信充值',
                        ]);
                        PayLog::payFinish($message);
                        // 修改会员折扣
                        $discount = model('recharge_template')->where('id',$payOrder['recharge_id'])->value('discount');
                        if(bccomp($member['discount'], $discount) === 1) {
                            $member->discount = $discount;
                        }
                        // 增加会员余额
                        $member->balance = bcadd($member->balance, $message['total_fee']/100);
                        $member->save();
                        $money = $message['total_fee']/100;
                        Message::create(['content'=>"车主:{$member->member_name},完成一笔{$money}元充值"]);//发送站内信
                        Db::commit();
                        Queue::push(Clue::class,['member_id'=>$payOrder['member_id'],'event_type'=>2,'props'=>['pay_amount'=>intval($message['total_fee'])]],'message');//充值付费
                        $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
                        foreach ($admins as $v){
                            Queue::push(\app\job\Message::class,[
                                'member_id'=>$v['member_id'],
                                'template_id'=>config('wechat_gzh')['gzh_template']['recharge_success'],
                                'data'=>[
                                    'amount1'=>$money,
                                    'amount2'=>$member->balance,
                                    'character_string4'=>$message['out_trade_no'],
                                    'time5'=>date('Y-m-d H:i'),
                                    'thing11'=>$member->member_name
                                ]
                            ],'message');
                        }
                        return true;// 返回处理完成
                    }catch (Exception $e){
                        Db::rollback();
                        Log::error('支付回调处理失败' . $e->getMessage());
                    }
                } elseif ($message['result_code'] === 'FAIL') {// 用户支付失败
                    return false;
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });
        $response->send();
    }


    public function set_menu(){
        try{
            $wxConfig = config('wechat_gzh');
            $app = Factory::officialAccount($wxConfig);
            $menu = $app->menu;
            $buttons = [
                [
                    "type" => "miniprogram",
                    "name" => "我要洗车",
                    "appid"  => "wx4bd6b93f69f561d8",
                    "url"=> "https://xm.xmlhzx.cn",
                    "pagepath"=>"pages/client/index/index",
                ],
                [
                    "type" => "miniprogram",
                    "name" => "商机",
                    "appid"  => "wx4bd6b93f69f561d8",
                    "url"=> "https://xm.xmlhzx.cn",
                    "pagepath"=>"pages/public/business/index",
                ],
                [
                    "type" => "miniprogram",
                    "name" => "我的",
                    "appid"  => "wx4bd6b93f69f561d8",
                    "url"=> "https://xm.xmlhzx.cn",
                    "pagepath"=>"pages/client/mine/index",
                ],
            ];
            $setRes = $menu->create($buttons);
            echo json_encode($setRes, JSON_UNESCAPED_UNICODE);
        }catch (Exception $e){
            echo $e->getMessage();
        }

    }

}
